'use strict';
const {
	log
} = require('console');
// 通过 require 引入 vk 实例
const vk = require('vk-unicloud');
const fs = require('fs');
const crypto = require('crypto');
const path = require('path');
const {
	Buffer
} = require('buffer');
// 通过 vk.init 初始化 vk实例（只有初始化后才能使用）
vk.init({
	baseDir: __dirname,
	requireFn: require
});

exports.main = async (event, context) => {
	const db = uniCloud.database();
	const _ = db.command;
	//event为客户端上传的参数
	console.log('http支付回调 : ', event)
	//为防止伪造，验证签名signature，如果和返回值里的event.body.signature一致，校验通过
	// let token = "4c20282cb2673e77ecb7ce61911c2f41b1a9ec26";
	// console.log("获取的参数headers", event.headers['byte-nonce-str']);

	let parms = JSON.parse(event.body) //获取报文主体
	let pay_channel = JSON.parse(parms.msg).pay_channel || 0 //枚举
	console.log('event为http支付回调', parms)


	let appid = JSON.parse(parms.msg).app_id;
	let channel_pay_id = JSON.parse(parms.msg).channel_pay_id //渠道单号
	let user_bill_pay_id = JSON.parse(parms.msg).user_bill_pay_id //商户订单号

	console.log("appid", appid);

	// 查询token  
	let restoken = await vk.baseDao.select({
		dbName: "a_appid", // 表名
		whereJson: { // 条件
			appid: appid
		},
	});

	console.log("res1", restoken);

	console.log("res2", restoken.rows[0].appsecret);


	//为防止伪造，验证签名signature，如果和返回值里的event.body.signature一致，校验通过
	// let token = "4a0d08cb5480d345036821177294a37503e635e7";

	let token = restoken.rows[0].appsecret;

	let publicKey = restoken.rows[0].publicKey;
	console.log("publicKey", publicKey);


	let paramd_msg = JSON.parse(parms.msg)

	// 输出 Node.js 版本
	console.log("Node.js 版本：", process.version);



	function verify(httpBody, publicKey, signStr, timestamp, nonce) {
		const buffer = Buffer.from(`${timestamp}\n${nonce}\n${httpBody}\n`, 'utf-8');
		const message = buffer.toString();
		crypto.getHashes(); // 这行代码会列出所有支持的哈希算法
		// console.log("砍砍看卡门卡门", crypto.getHashes());
		const verifier = crypto.createVerify('RSA-SHA256');
		verifier.update(message);

		const publicKeyObject = stringToPublicKey(publicKey);
		const signatureBuffer = Buffer.from(signStr, 'base64');

		return verifier.verify(publicKeyObject, signatureBuffer);
	}

	function stringToPublicKey(publicKey) {
		// const decoded = Buffer.from(publicKey, 'base64');
		// return crypto.createPublicKey(decoded);
		// 移除不必要的换行符和空格
		const cleanedKey = publicKey.replace(/\s/g, '');
		// 添加 PEM 头和尾
		const pemFormattedKey = `-----BEGIN PUBLIC KEY-----\n${cleanedKey}\n-----END PUBLIC KEY-----`;
		// 创建 PublicKey 对象
		return crypto.createPublicKey(pemFormattedKey);
	}
	var userInfo = {};

	const httpBody = event.body; // 从应答中获取报文主体;

	// const publicKey =
	// 	'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuRjIMJcWFz27LOAjJW9/7c9UpNAVOAB49B1A2er3kpjaD2/urI80GNA0xSjpd6AjCLBQGlmBU/noeVTuz4V0vh5nown7BCjkvZuzOKB/BzbJlJuK7oCl06ki7AepibJm4/KUt5VG/7T4LajU7GSdBMrpczQ3c8vJEu7oqg7sNFt0WAfrHLnZ8BxMOO2Iywh7KpqCAt/oveeVnxGyCrcbcCseq+cnPYKL+DBfxaFffQzdDVZ46kmMDZ1GgSmcdpaHJcybYHMvcDFLPoG3cKjXVIPlkwqE0wYPq6UXm4gRaMvhB1As2XYkj2g7FlgkJlqr8RRo7b/b9OxPTPswdzwJ6wIDAQAB';

	const signStr = event.headers['byte-signature'];

	const timestamp = event.headers['byte-timestamp']; // 从应答 HTTP 头 Byte-Timestamp 获取

	const nonce = event.headers['byte-nonce-str']; // 从应答 HTTP 头 Byte-Nonce-Str 获取

	const result = verify(httpBody, publicKey, signStr, timestamp, nonce);

	console.log("result", result);
	// 如果签名失败， 则直接返回
	if (!result) {
		console.log("签名校验失败");
		let res = {
			"err_no": 1,
			"err_tips": "fail"
		}
		return res
	}

	//如果算出来的签名和支付系统返回的签名一致，说明请求来源正常


	console.log("hhhhhhh", paramd_msg.out_order_no);
	const order_temp = await db.collection('a_recharge').where({
		out_trade_no: paramd_msg.out_order_no
	}).get()
	const orderinfo = order_temp.data[0]
	console.log("orderinfo", orderinfo);
	if (paramd_msg.status == 'SUCCESS' && orderinfo.pay_status == 0) {

		const newInfo = await db.collection('uni-id-users').where({
			_id: orderinfo.user_id
		}).get()

		console.log("newInfo=", newInfo);
		userInfo = newInfo;

		let nowtime = new Date().getTime()

		if (orderinfo.subject == "充值金豆" && orderinfo.pay_status == 0) {
			//如果修改成功，给用户增加金豆数量
			const order_tempmm = await db.collection('a_jindou_detail').where({
				out_trade_no: paramd_msg.out_order_no,
			}).get()

			console.log("order_temp=========", order_tempmm);


			if (order_tempmm.data.length == 0) {


				//添加金豆收支明细
				const add_jindou = await db.collection('a_jindou_detail').add({
					out_trade_no: paramd_msg.out_order_no,
					user_id: orderinfo.user_id,
					nickname: orderinfo.nickname || "匿名",
					change_num: orderinfo.bean, //增加的金豆数量
					change_reason: "抖音支付" + paramd_msg.total_amount + "分钱充值" + orderinfo.bean + "金豆",
					type: "income", //类型：expend:支出,income:收入。
					_add_time: nowtime
				})


				let newInfo = await vk.baseDao.updateAndReturn({
					dbName: "uni-id-users",
					whereJson: {
						_id: orderinfo.user_id
					},
					dataJson: {
						balance: _.inc(orderinfo.bean),
						is_paid: true,
						had_youhui: true, //had_youhui可以判断用户是否付费过，便于付费用户数量统计
						order_id: paramd_msg.order_id
					}
				});
				console.log("newInfo=", newInfo);

				console.log("ad_id=", userInfo.ad_id);
				console.log("clickid=", userInfo.clickid);



				//添加操作日志
				const addlog = await db.collection('a_log').add({
					user_id: orderinfo.user_id || '无',
					operator: "抖音支付回调云函数recharge",
					event: "支付" + paramd_msg.total_amount + "分钱充值" + orderinfo.bean + "金豆",
					_add_time: nowtime
				})
			}
		}
		if (orderinfo.subject == "单剧会员") {
			let newInfo = await vk.baseDao.updateAndReturn({
				dbName: "uni-id-users",
				whereJson: {
					_id: orderinfo.user_id
				},
				dataJson: {
					is_paid: true,
					had_youhui: true, //had_youhui可以判断用户是否付费过，便于付费用户数量统计
					order_id: paramd_msg.order_id
				}
			});
			//添加金豆收支明细
			let add_djhy = await db.collection('a_djhy').add({
				user_id: orderinfo.user_id,
				nickname: orderinfo.nickname || "未绑定",
				tv_name: orderinfo.tv_name,
				tv_id: orderinfo.tv_id,
				appid: orderinfo.appid || "",
				appname: orderinfo.appname || "",
				_add_time: nowtime
			})
		}
		if (orderinfo.subject == "自定义会员" && orderinfo.pay_status == 0) {
			let addtime = 0;
			const onedaytime = 86400000 //1天
			const onehourtime = 3600000 //1小时
			if (orderinfo.days) {
				addtime = onedaytime * orderinfo.days
			}
			if (orderinfo.hour) {
				addtime = onehourtime * orderinfo.hour
			}
			//先查询用户信息，是否已是会员
			let getres = await db.collection('uni-id-users').doc(orderinfo.user_id).field({
				plus_expire_time: true
			}).get()

			const plus_expire = getres.data[0].plus_expire_time
			if (plus_expire * 1 < nowtime * 1) {
				let new_expire_time = nowtime * 1 + addtime;
				//如果会员已到期，会员时间就是当前时间+addtime
				let updateVip = await db.collection('uni-id-users').doc(orderinfo.user_id).update({
					is_paid: true, //记录用户已支付
					plus_type: 1,
					plus_expire_time: new_expire_time
				})
			} else {
				console.log("修改用户会员到期时间");
				let new_expire_time2 = plus_expire * 1 + addtime
				//如果会员没有到期，会员时间就是到期时间+addtime
				let updateVip2 = await db.collection('uni-id-users').doc(orderinfo.user_id).update({
					is_paid: true, //记录用户已支付
					plus_expire_time: new_expire_time2
				})
			}

			//添加操作日志
			const addlog2 = await db.collection('a_log').add({
				user_id: orderinfo.user_id || '无',
				operator: "抖音支付回调云函数recharge",
				event: "自定义会员",
				_add_time: nowtime
			})
		}
		if (orderinfo.subject == "开通会员" || orderinfo.subject == "年度会员" || orderinfo.subject == "季度会员" ||
			orderinfo.subject ==
			"月度会员") {

			let addtime = 0;
			//【开通会员】这个类型是为了兼容老版本的年费会员
			if (orderinfo.subject == "开通会员" && orderinfo.pay_status == 0) {
				addtime = 31536000000 //365天
			}
			if (orderinfo.subject == "年度会员" && orderinfo.pay_status == 0) {
				addtime = 31536000000 //365天
			}
			if (orderinfo.subject == "季度会员" && orderinfo.pay_status == 0) {
				addtime = 7776000000 //90天
			}
			if (orderinfo.subject == "月度会员" && orderinfo.pay_status == 0) {
				addtime = 2592000000 //30天
			}

			//先查询用户信息，是否已是会员
			const get_plus_expire_time = await db.collection('uni-id-users').doc(orderinfo.user_id).field({
				plus_expire_time: true
			}).get()


			const plus_expire = get_plus_expire_time.data[0].plus_expire_time

			console.log("plus_expire", plus_expire);
			if (plus_expire * 1 < nowtime * 1) {
				let new_expire_time = nowtime * 1 + addtime;
				console.log("orderinfo.user_id", orderinfo.user_id);
				console.log("new_expire_time", new_expire_time);
				const updateUser = await db.collection('uni-id-users').doc(orderinfo.user_id).update({
					is_paid: true,
					plus_type: 1,
					plus_expire_time: new_expire_time
				})
			} else {
				console.log("修改用户会员到期时间");
				let new_expire_time2 = plus_expire * 1 + addtime
				//如果会员没有到期，会员时间就是到期时间+365天
				const updateUser2 = await db.collection('uni-id-users').doc(orderinfo.user_id).update({
					is_paid: true,
					plus_expire_time: new_expire_time2
				})
			}
			//添加操作日志
			const addlog2 = await db.collection('a_log').add({
				user_id: orderinfo.user_id || '无',
				operator: "抖音支付回调云函数recharge",
				event: "开通一年会员",
				_add_time: nowtime
			})
		}

		//修改充值记录订单，状态为已支付，并记录实付金额，微信支付订单号等
		const update_order = await db.collection('a_recharge').where({
			out_trade_no: paramd_msg.out_order_no
		}).update({
			pay_channel: pay_channel || 0,
			channel_pay_id,
			user_bill_pay_id,
			shifu_amount: paramd_msg.total_amount || 0,
			transaction_id: paramd_msg.channel_no || "transaction_id",
			payment_order_no: paramd_msg.payment_order_no || "payment_order_no",
			tt_order_id: paramd_msg.order_id || "tt_order_id",
			pay_status: 1,
			settle: 0, //分账状态，0为未分账，1为已分账
			ad_id: userInfo.ad_id, //如果是来自巨量投流的用户，会在该用户信息里绑定ad_id
			clickid: userInfo.clickid, //如果是来自巨量投流的用户，会在该用户信息里绑定clickid，用于回传数据
			// recharge_all: recharge_all + 1,  // 支付次数加 1
			_add_time: nowtime,
			is_first: true // 首笔为 true
		})

		// 查询用户用户支付次数
		// let recharge_all = await vk.baseDao.count({
		// 	dbName: "a_recharge", // 表名
		// 	whereJson: { // 条件
		// 		pay_status: 1,
		// 		user_id: orderinfo.user_id,
		// 	}
		// });


		//======获取回传比例开始======

		// 将时间戳转换为年月日格式
		const date = new Date(nowtime);
		const year = date.getFullYear();
		const month = String(date.getMonth() + 1).padStart(2, "0");
		const day = String(date.getDate()).padStart(2, "0");
		const hours = String(date.getHours()).padStart(2, "0");
		const minutes = String(date.getMinutes()).padStart(2, "0");
		const seconds = String(date.getSeconds()).padStart(2, "0");

		let formattedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
		console.log("年月日====", formattedDate);

		// 添加日志
		async function addvktest(tips) {
			let addvktest = await db.collection('callback_log').add({
				tips: tips,
				out_trade_no: paramd_msg.out_order_no, //充值订单号
				total_fee: paramd_msg.total_amount, //支付金额
				_add_time: nowtime,
				_add_time_str: formattedDate
			})
		}

		console.log("订单信息======", orderinfo);
		let percent = null
		let tfurlpercent = await db.collection('a_config').where({
			name: "RebackPercent",
			tfid: orderinfo.tfid //添加这条数据的代理商ID
		}).get()
		console.log("tfurlpercent====", tfurlpercent);


		if (tfurlpercent.data.length != 0) {
			percent = tfurlpercent
		} else {
			percent = await db.collection('a_config').where({
				name: "RebackPercent",
				user_id: orderinfo.invite_code || 0 //添加这条数据的代理商ID
			}).get()
		}
		console.log("percent=====", percent);

		let douyinRadio = 0; //默认回传模式为百分比（概率回传）

		// let douyin_ReturnRatio = 0;
		// let douyin_UnReturnRatio = 0;
		// let firstorder = false;
		// let douyinMaxPrice = 0
		// let douyinMinPrice = 0

		if (percent.data[0]) {
			console.log("存在代理商比例数据", percent);
			douyinRadio = percent.data[0].douyinRadio || 0; //抖音回传模式
			// douyin_ReturnRatio = percent.data[0].douyin_ReturnRatio || 0; //抖音上传比例
			// douyin_UnReturnRatio = percent.data[0].douyin_UnReturnRatio || 0; //抖音不上传比例
			// firstorder = percent.data[0].firstorder;
			// douyinMaxPrice = percent.data[0].douyinMaxPrice || 0;
			// douyinMinPrice = percent.data[0].douyinMinPrice || 0;
		} else {
			console.log("不存在代理商比例数据");
		}


		//   判断回传模式

		// 比例回传
		await vk.callFunction({
			name: "hedian",
			url: 'client/user/pub/proportional_callabck',
			title: '请求中...',
			data: {
				out_trade_no: paramd_msg.out_order_no, //充值订单号
				total_fee: paramd_msg.total_amount, //支付金额
				_add_time: nowtime,
				_add_time_str: formattedDate,
				percent: percent
			},
		});
		await addvktest("进行了比例回传");



		let res = {
			"err_no": 0,
			"err_tips": "success"
		}
		//返回数据给客户端
		return res

	} else {
		console.log("用户取消支付或者用户已经产生了回调");
		let res = {
			"err_no": 0,
			"err_tips": "success"
		}
		return res
	}

	return res
};